<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="emit('update:visible', $event)"
    title="评价订单"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="review-content">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="评分" prop="rating">
          <el-rate
            v-model="formData.rating"
            :max="5"
            show-score
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
          />
        </el-form-item>

        <el-form-item label="评价内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="4"
            placeholder="请输入您的评价内容"
          />
        </el-form-item>

        <el-form-item label="上传照片">
          <el-upload
            class="image-uploader"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handleImageChange"
            :before-upload="beforeUpload"
            :file-list="fileList"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="匿名评价">
          <el-switch v-model="formData.is_anonymous" />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">提交评价</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="imagePreviewDialogVisible">
    <img w-full :src="imagePreviewDialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue'
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { createReview } from '@/api/review'
import { uploadReviews, uploadSamples } from '@/api/upload'
import { v4 as uuidv4 } from 'uuid'
import { beforeUpload } from '@/utils/upload'
import type { FileItem, UploadFile } from '@/types/upload'

const props = defineProps<{
  visible: boolean
  orderId: number
}>()

const emit = defineEmits(['update:visible', 'success'])

const formRef = ref<FormInstance>()
const loading = ref(false)
const fileList = ref<UploadUserFile[]>([])

const imagePreviewDialogVisible = ref(false)
const imagePreviewDialogImageUrl = ref('')

const formData = ref({
  rating: undefined,
  content: '',
  is_anonymous: false,
})

const rules: FormRules = {
  rating: [{ required: true, message: '请选择评分', trigger: 'change' }],
  content: [
    { required: true, message: '请输入评价内容', trigger: 'blur' },
    { min: 10, message: '评价内容至少10个字符', trigger: 'blur' },
  ],
}

const handleImageChange = (file: UploadFile) => {
  if (!beforeUpload(file.raw)) return

  // 创建预览URL
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = async () => {
    const newFile: FileItem = {
      uid: uuidv4(),
      name: file.name,
      url: reader.result as string,
      status: 'ready',
      raw: file.raw,
    }

    try {
      if (!newFile.raw) {
        ElMessage.error('请选择文件')
        return
      }

      newFile.status = 'uploading'
      newFile.percentage = 0

      const response = await uploadReviews([newFile.raw], (percentage) => {
        newFile.percentage = percentage
      })

      newFile.status = 'success'
      fileList.value.push({
        name: response.data.data.files[0].filename,
        url: response.data.data.files[0].url,
      } as UploadUserFile)
      ElMessage.success('上传成功')
    } catch (error) {
      newFile.status = 'error'
      ElMessage.error('上传失败')
    }
  }
}

const handleRemove = (file: UploadUserFile) => {
  const index = fileList.value.findIndex((item) => item.url === file.url)
  if (index > -1) {
    fileList.value.splice(index, 1)
  }
}

const handlePictureCardPreview = (file: UploadUserFile) => {
  imagePreviewDialogImageUrl.value = file.url!
  imagePreviewDialogVisible.value = true
}

// 提交评价
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 提交评价
        await createReview({
          order_id: props.orderId,
          rating: formData.value.rating!,
          content: formData.value.content,
          photos: fileList.value.map((item) => item.url!),
          is_anonymous: formData.value.is_anonymous,
        })

        ElMessage.success('评价提交成功')
        emit('success')
        emit('update:visible', false)
      } catch (error) {
        ElMessage.error('评价提交失败')
      } finally {
        loading.value = false
      }
    }
  })
}

const handleCancel = () => {
  emit('update:visible', false)
}
</script>

<style scoped>
.review-content {
  padding: 20px;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
</style>
